'use strict';

module.exports = () => async (ctx, next) => {
  ctx.userId = '';
  ctx.role = '';
  ctx.jwterror = '';
  const token = ctx.get('Authorization');

  // 直接传yc-user-id 是为了测试环境方便测试  应该改为token解析出user-id
  if (ctx.app.config.env !== 'prod') {
    const userId = ctx.get('yc-user-id');
    if (userId && userId !== 'undefined') {
      ctx.userId = ctx.get('yc-user-id') || '';
    }
    ctx.merchantId = ctx.get('yc-merchant-id');
    ctx.merchantStaffId = ctx.get('yc-merchant-staff-id');
    ctx.designatedPlatId = ctx.get('yc-designated-plat-id');
    ctx.designatedStaffId = ctx.get('yc-designated-staff-id');
    ctx.driverPlatId = ctx.get('yc-driver-plat-id');
    ctx.operatorStaffId = ctx.get('yc-operate-staff-id');
  }

  if (token) {
    try {
      const {
        user,
        role,
        merchantId,
        isolation,
        designatedStaffId,
        designatedPlatId,
      } = await ctx.helper.verify(token);

      const redisToken = await ctx.app.redis.get(`user_id:${user}`);
      if (redisToken === token) {
        ctx.userId = user;
        ctx.role = role;
        ctx.merchantId = merchantId;
        ctx.designatedPlatId = designatedPlatId;
        ctx.designatedStaffId = designatedStaffId;
        ctx.isolation = isolation || '';
      }
    } catch (e) {
      ctx.throw(401, { code: -402, message: 'token失效' });
    }
  }
  await next();
};
